package com.example.emos.wx;

import cn.hutool.core.util.StrUtil;
import com.example.emos.wx.config.SystemConstants;
import com.example.emos.wx.db.dao.SysConfigDao;
import com.example.emos.wx.db.pojo.SysConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;

import javax.annotation.PostConstruct;
import java.io.File;
import java.lang.reflect.Field;
import java.util.List;

@SpringBootApplication
@ServletComponentScan
@Slf4j
@EnableAsync //开启异步多线程执行
public class EmosWxApiApplication {

    @Autowired
    private SysConfigDao sysConfigDao;

    @Autowired
    private SystemConstants constants;

    @Value("${emos.image-folder}")
    private String imageFolder;

    public static void main(String[] args) {
        SpringApplication.run(EmosWxApiApplication.class, args);
    }

    /**
     * 初始化方法
     */
    @PostConstruct
    public void init() {
        List<SysConfig> list = sysConfigDao.selectAllParam(); // 查询各个时间的常量数据并保存
        list.forEach(one -> {   // forEach 每次取出一个数据赋值给 one
            String key = one.getParamKey();  // 取出pojo对象的常量名
            key = StrUtil.toCamelCase(key);  // 转换为驼峰命名法
            String value = one.getParamValue(); // 取出常量值
            try {
                Field field = constants.getClass().getDeclaredField(key); //根据常量名在封装类中查找变量
                field.set(constants, value); // 对查找到的变量进行赋值
            } catch (Exception e) {
                log.error("执行异常", e); // 没找到变量 抛出异常
            }
        });
        new File(imageFolder).mkdirs(); // 根据路径查找文件夹,没有就创建
    }
}
